{% extends "base.html" %}

{% block title %}课程管理 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    
    .search-box {
        padding: 0.5rem 1rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        width: 300px;
    }
    
    .courses-table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .courses-table th,
    .courses-table td {
        padding: 0.75rem;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .courses-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .courses-table tr:hover {
        background: #f8f9fa;
    }
    
    .action-btn {
        padding: 0.25rem 0.75rem;
        margin: 0 0.25rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.85rem;
    }
    
    .btn-edit {
        background: #3498db;
        color: white;
    }
    
    .btn-delete {
        background: #e74c3c;
        color: white;
    }
    
    .btn-view {
        background: #2ecc71;
        color: white;
    }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
    }
    
    .modal-content {
        background: white;
        max-width: 600px;
        margin: 5% auto;
        padding: 2rem;
        border-radius: 8px;
        max-height: 80vh;
        overflow-y: auto;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
    }
    
    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
    }
    
    .form-group textarea {
        min-height: 100px;
        resize: vertical;
    }
    
    .tag-badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        background: #3498db;
        color: white;
        border-radius: 12px;
        font-size: 0.8rem;
        margin: 0 0.25rem;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">课程管理</h2>

<div class="card">
    <div class="toolbar">
        <input type="text" id="search-input" class="search-box" placeholder="搜索课程名称或代码...">
        <button class="btn btn-primary" onclick="showCreateModal()">+ 创建课程</button>
    </div>
    
    <div id="loading" class="loading" style="display:none;">
        <div class="spinner"></div>
        <p>加载中...</p>
    </div>
    
    <table class="courses-table" id="courses-table">
        <thead>
            <tr>
                <th>课程代码</th>
                <th>课程名称</th>
                <th>学分</th>
                <th>院系</th>
                <th>学期</th>
                <th>授课教师</th>
                <th>选课人数</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="courses-tbody">
        </tbody>
    </table>
</div>

<!-- 课程详情模态框 -->
<div id="view-modal" class="modal">
    <div class="modal-content">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.5rem;">
            <h3>课程详情</h3>
            <button onclick="closeViewModal()" style="border:none;background:none;font-size:1.5rem;cursor:pointer;">&times;</button>
        </div>
        <div id="course-detail-content"></div>
        <div style="margin-top:1.5rem;text-align:right;">
            <button class="btn btn-primary" onclick="closeViewModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 创建/编辑课程模态框 -->
<div id="course-modal" class="modal">
    <div class="modal-content">
        <h3 id="modal-title">创建课程</h3>
        <form id="course-form" onsubmit="return false;">
            <input type="hidden" id="course-id">
            
            <div class="form-group">
                <label>课程代码 *</label>
                <input type="text" id="course-code" required>
            </div>
            
            <div class="form-group">
                <label>课程名称 *</label>
                <input type="text" id="course-name" required>
            </div>
            
            <div class="form-group">
                <label>课程描述</label>
                <textarea id="description"></textarea>
            </div>
            
            <div class="form-group">
                <label>学分 *</label>
                <input type="number" id="credits" step="0.5" min="0" max="10" required>
            </div>
            
            <div class="form-group">
                <label>院系</label>
                <select id="department">
                    <option value="">请选择</option>
                    <option value="计算机学院">计算机学院</option>
                    <option value="软件学院">软件学院</option>
                    <option value="人工智能学院">人工智能学院</option>
                    <option value="网络空间安全学院">网络空间安全学院</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>学年</label>
                <input type="text" id="academic-year" placeholder="例如: 2023-2024">
            </div>
            
            <div class="form-group">
                <label>学期</label>
                <select id="semester-term">
                    <option value="">请选择</option>
                    <option value="1">第一学期</option>
                    <option value="2">第二学期</option>
                    <option value="3">第三学期</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>授课教师</label>
                <select id="instructor-id">
                    <option value="">请选择</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>最大选课人数</label>
                <input type="number" id="max-students" min="0">
            </div>
            
            <div class="form-group">
                <label>标签 (逗号分隔)</label>
                <input type="text" id="tags" placeholder="例如: Python, 编程, 基础">
            </div>
            
            <div style="display:flex;gap:1rem;margin-top:1.5rem;">
                <button type="button" class="btn btn-primary" onclick="saveCourse()" style="flex:1;">保存</button>
                <button type="button" class="btn btn-danger" onclick="closeModal()" style="flex:1;">取消</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let allCourses = [];
    let allTeachers = [];
    
    async function loadCourses() {
        try {
            document.getElementById('loading').style.display = 'block';
            
            const data = await apiRequest('/courses?page=1&per_page=100');
            
            if (data.success) {
                allCourses = data.data;
                renderCourses(allCourses);
            }
            
            document.getElementById('loading').style.display = 'none';
        } catch (error) {
            showAlert('加载课程失败: ' + error.message, 'error');
            document.getElementById('loading').style.display = 'none';
        }
    }
    
    async function loadTeachers() {
        try {
            const data = await apiRequest('/teachers?page=1&per_page=100');
            
            if (data.success) {
                allTeachers = data.data;
                
                const select = document.getElementById('instructor-id');
                select.innerHTML = '<option value="">请选择</option>' + 
                    allTeachers.map(t => `
                        <option value="${t.id}">${t.last_name}${t.first_name} (${t.username})</option>
                    `).join('');
            }
        } catch (error) {
            console.error('加载教师失败:', error);
        }
    }
    
    function renderCourses(courses) {
        const tbody = document.getElementById('courses-tbody');
        
        if (courses.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = courses.map(course => `
            <tr>
                <td>${course.code}</td>
                <td>${course.name}</td>
                <td>${course.credits}</td>
                <td>${course.department || '-'}</td>
                <td>${formatSemester(course)}</td>
                <td>${course.instructor_id ? '已分配' : '未分配'}</td>
                <td>${course.enrollment_count || 0}</td>
                <td>
                    <button class="action-btn btn-view" onclick="viewCourse(${course.id})">查看</button>
                    <button class="action-btn btn-edit" onclick="editCourse(${course.id})">编辑</button>
                    <button class="action-btn btn-delete" onclick="deleteCourse(${course.id}, '${course.code}')">删除</button>
                </td>
            </tr>
        `).join('');
    }
    
    function showCreateModal() {
        document.getElementById('modal-title').textContent = '创建课程';
        document.getElementById('course-form').reset();
        document.getElementById('course-id').value = '';
        document.getElementById('course-code').readOnly = false;
        document.getElementById('course-modal').style.display = 'block';
    }
    
    async function editCourse(courseId) {
        try {
            const data = await apiRequest(`/courses/${courseId}`);
            
            if (data.success) {
                const course = data.data;
                
                document.getElementById('modal-title').textContent = '编辑课程';
                document.getElementById('course-id').value = course.id;
                document.getElementById('course-code').value = course.code;
                document.getElementById('course-code').readOnly = true;
                document.getElementById('course-name').value = course.name;
                document.getElementById('description').value = course.description || '';
                document.getElementById('credits').value = course.credits;
                document.getElementById('department').value = course.department || '';
                document.getElementById('academic-year').value = course.academic_year || '';
                document.getElementById('semester-term').value = course.semester_term || '';
                document.getElementById('instructor-id').value = course.instructor_id || '';
                document.getElementById('max-students').value = course.max_students || '';
                document.getElementById('tags').value = course.tags ? course.tags.join(', ') : '';
                
                document.getElementById('course-modal').style.display = 'block';
            }
        } catch (error) {
            showAlert('加载课程详情失败: ' + error.message, 'error');
        }
    }
    
    async function viewCourse(courseId) {
        try {
            // 显示加载状态
            document.getElementById('course-detail-content').innerHTML = '<div class="loading"><div class="spinner"></div><p>加载中...</p></div>';
            document.getElementById('view-modal').style.display = 'block';
            
            // 获取课程详情
            const courseData = await apiRequest(`/courses/${courseId}`);
            
            if (courseData.success) {
                const course = courseData.data;
                
                // 获取课程统计信息
                const statsData = await apiRequest(`/analytics/courses/${courseId}/statistics`);
                const stats = statsData.success ? statsData.data.statistics : null;
                
                // 构建详情HTML
                let html = `
                    <div style="line-height:1.8;">
                        <div style="margin-bottom:1.5rem;padding-bottom:1rem;border-bottom:2px solid #e0e0e0;">
                            <h4 style="color:#2c3e50;margin-bottom:0.5rem;">${course.code} - ${course.name}</h4>
                            <div style="color:#7f8c8d;font-size:0.9rem;">${course.description || '暂无描述'}</div>
                        </div>
                        
                        <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:1rem;margin-bottom:1rem;">
                            <div>
                                <strong>学分：</strong>${course.credits}
                            </div>
                            <div>
                                <strong>院系：</strong>${course.department || '-'}
                            </div>
                            <div>
                                <strong>学期：</strong>${formatSemester(course)}
                            </div>
                            <div>
                                <strong>最大人数：</strong>${course.max_students || '-'}
                            </div>
                            <div>
                                <strong>选课人数：</strong><span style="color:#3498db;font-weight:600;">${course.enrollment_count || 0}</span>
                            </div>
                            <div>
                                <strong>授课教师：</strong>${course.instructor ? course.instructor.last_name + course.instructor.first_name : '未分配'}
                            </div>
                        </div>
                        
                        ${course.tags && course.tags.length > 0 ? `
                        <div style="margin-bottom:1rem;">
                            <strong>课程标签：</strong>
                            ${course.tags.map(tag => `<span class="badge" style="background:#3498db;color:white;padding:0.25rem 0.5rem;border-radius:4px;margin:0.25rem;display:inline-block;">${tag}</span>`).join('')}
                        </div>
                        ` : ''}
                        
                        ${stats ? `
                        <div style="margin-top:1.5rem;padding-top:1rem;border-top:2px solid #e0e0e0;">
                            <h4 style="color:#2c3e50;margin-bottom:1rem;">📊 课程统计</h4>
                            <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:1rem;background:#f8f9fa;padding:1rem;border-radius:8px;">
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">总选课人数</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#3498db;">${stats.total_enrolled}</div>
                                </div>
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">已完成</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#2ecc71;">${stats.completed}</div>
                                </div>
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">退课人数</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#e74c3c;">${stats.dropped}</div>
                                </div>
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">完成率</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#9b59b6;">${stats.completion_rate.toFixed(1)}%</div>
                                </div>
                                ${stats.average_score ? `
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">平均分</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#f39c12;">${stats.average_score.toFixed(2)}</div>
                                </div>
                                <div>
                                    <div style="font-size:0.85rem;color:#7f8c8d;">及格率</div>
                                    <div style="font-size:1.5rem;font-weight:600;color:#16a085;">${stats.pass_rate.toFixed(1)}%</div>
                                </div>
                                ` : ''}
                            </div>
                        </div>
                        ` : ''}
                    </div>
                `;
                
                document.getElementById('course-detail-content').innerHTML = html;
            }
        } catch (error) {
            document.getElementById('course-detail-content').innerHTML = `<div style="color:#e74c3c;text-align:center;padding:2rem;">加载失败: ${error.message}</div>`;
        }
    }
    
    function closeViewModal() {
        document.getElementById('view-modal').style.display = 'none';
    }
    
    async function saveCourse() {
        try {
            const courseId = document.getElementById('course-id').value;
            const isEdit = !!courseId;
            
            const courseData = {
                code: document.getElementById('course-code').value,
                name: document.getElementById('course-name').value,
                description: document.getElementById('description').value,
                credits: parseFloat(document.getElementById('credits').value),
                department: document.getElementById('department').value,
                academic_year: document.getElementById('academic-year').value,
                semester_term: document.getElementById('semester-term').value,
                max_students: parseInt(document.getElementById('max-students').value) || null,
                tags: document.getElementById('tags').value
            };
            
            const instructorId = document.getElementById('instructor-id').value;
            if (instructorId) {
                courseData.instructor_id = parseInt(instructorId);
            }
            
            const url = isEdit ? `/courses/${courseId}` : '/courses';
            const method = isEdit ? 'PUT' : 'POST';
            
            const data = await apiRequest(url, {
                method: method,
                body: JSON.stringify(courseData)
            });
            
            if (data.success) {
                showAlert(isEdit ? '课程更新成功' : '课程创建成功', 'success');
                closeModal();
                loadCourses();
            }
        } catch (error) {
            showAlert('操作失败: ' + error.message, 'error');
        }
    }
    
    async function deleteCourse(courseId, courseCode) {
        if (!confirm(`确定要删除课程 "${courseCode}" 吗？此操作不可恢复！`)) {
            return;
        }
        
        try {
            const data = await apiRequest(`/courses/${courseId}`, {
                method: 'DELETE'
            });
            
            if (data.success) {
                showAlert('课程删除成功', 'success');
                loadCourses();
            }
        } catch (error) {
            showAlert('删除失败: ' + error.message, 'error');
        }
    }
    
    function closeModal() {
        document.getElementById('course-modal').style.display = 'none';
    }
    
    // 搜索功能
    document.getElementById('search-input')?.addEventListener('input', (e) => {
        const keyword = e.target.value.toLowerCase();
        const filtered = allCourses.filter(course => 
            course.name.toLowerCase().includes(keyword) ||
            course.code.toLowerCase().includes(keyword) ||
            (course.department && course.department.toLowerCase().includes(keyword))
        );
        renderCourses(filtered);
    });
    
    // 页面加载
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'admin') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadCourses();
        loadTeachers();
    });
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        const courseModal = document.getElementById('course-modal');
        const viewModal = document.getElementById('view-modal');
        
        if (event.target === courseModal) {
            closeModal();
        } else if (event.target === viewModal) {
            closeViewModal();
        }
    }
</script>
{% endblock %}


